<template>
  <div class="video-container">
    <video class="webrtc-video" ref="videoRef"></video>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, nextTick } from "vue";

const props = defineProps({
  url: String,
  rtspUrl: String,
});

const webRtcServer = ref(null);
const videoRef = ref(null);

const init = () => {
  // 使用 nextTick 是为了确保 video 元素已经渲染到 DOM 中，以避免初始化 WebRtcStreamer 时找不到 video 元素的问题
  nextTick(() => {
    webRtcServer.value = new WebRtcStreamer(videoRef.value, props.url);
    webRtcServer.value.connect(props.rtspUrl);
  });
};

onMounted(() => {
  init();
});

onBeforeUnmount(() => {
  webRtcServer.value.disconnect();
  webRtcServer.value = null;
});
</script>

<script>
export default {
  name: "WebRtcVideo",
};
</script>

<style scoped>
.video-container {
  min-width: 600px;
  min-height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.webrtc-video {
  width: 100%;
  height: auto;
}
</style>
